package org.leiyang.common.util;

import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.util.CharsetUtil;
import org.leiyang.common.dtos.Message;
import org.leiyang.common.dtos.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MsgSendUtil {
    private static final Logger logger = LoggerFactory.getLogger(MsgSendUtil.class);

    /**
     * 将消息数据发送到netty server
     */
    public static void sendResponse(Channel channel, R<Message> reps, Boolean httpFormat) {
        // 表示非http格式，那就是发送TEXT格式
        final String repsStr = JSON.toJSONString(reps);
        if(!httpFormat) {
            //这里发送文本格式消息
            WebSocketFrame content = new TextWebSocketFrame(repsStr);
            channel.writeAndFlush(content).addListener(future -> {
                if (future.isSuccess()) {
                    logger.info("Msg Server端已发送消息到客户端: {}", repsStr);
                    return;
                }
                logger.error("Msg Server端发送Message是否成功: {}, 异常信息: ", future.isSuccess(), future.cause());
            });
            return;
        }
        // 构建响应内容
        byte[] content = repsStr.getBytes(CharsetUtil.UTF_8);
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        response.content().writeBytes(content);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        // 发送响应
        channel.writeAndFlush(response).addListener(future -> {
            if (future.isSuccess()) {
                logger.info("消息({})已开始发送到Netty Server", reps.getData());
            }
        });
    }
}
